<?php

/**
 * 表格处理
 *
 * @authors afree
 * @date    2019-01-23 15:37:58
 * @version $Id$
 */

namespace App\Tools;

class Texcel
{

    /**
     * 导出数据
     * 在浏览器输出并下载
     */
    public static function exportExcelHtml($title, $tArr = [], $dataArr = [], $height = 30, $width = 30)
    {
        if ($tArr && $dataArr) {
            //文件名
            $filename = $title . ".xls";
            $htmlStr = '';
            //生成HTML
            $htmlStr .= "<table border=1 style='text-align: center;'>";
            //生成头部
            $htmlStr .= "<tr>";
            foreach ($tArr as $value) {
                $htmlStr .= "<th>{$value}</th>";
            }
            $htmlStr .= "</tr>";

            //生成数据
            foreach ($dataArr as $key => $rt) {
                $htmlStr .= "<tr>";
                foreach ($rt as $k => $v) {
                    $htmlStr .= "<td height=" . $height . ">" . $v . "</td>";
                }
                $htmlStr .= "</tr>\n";
            }
            $htmlStr .= "</table></body></html>";

            //输出数据流
            header("Content-Type: application/vnd.ms-excel;charset=utf-8");
            header("Content-type: application/octet-stream");
            header("Content-Disposition: attachment; filename=" . $filename);
            header("Cache-Control: must-revalidate, post-check=0, pre-check=0");
            header("Pragma: no-cache");
            header("Expires: 0");

            exit($htmlStr);
        }
    }

    /**
     * 导出数据 fput
     * @param type $param
     */
    public static function exportCsvFile($file_name, $tArr = [], $dataArr = [], $num = 0)
    {
        $dataStr = '';
        $file_name = iconv('utf-8', 'gb2312', $file_name);
        if (file_exists($file_name) && $num == 1) {
            unlink($file_name);
        }
        if ($num == 1) {
            $dataStr .= implode(',', $tArr);
            $dataStr .= "\n"; //用引文逗号分开
        }
        foreach ($dataArr as $key => $value) {
            $dataStr .= implode(',', $value);
            $dataStr .= "\n"; //用引文逗号分开
        }
        $dataStr = iconv('utf-8', 'gb2312', $dataStr);
        ob_flush();
        flush();
        file_put_contents($file_name, $dataStr, FILE_APPEND);
    }

    /**
     * csv_get_lines 读取CSV文件中的某几行数据
     * @param $csvfile csv文件路径
     * @param $lines 读取行数
     * @param $offset 起始行数
     * @return array
     * */
    public static function getCsvLine($csvfile, $offset = 0, $lines = 1000)
    {
        if (!$fp = fopen($csvfile, 'r')) {
            return false;
        }
        $i = $j = 0;
        while (false !== ($line = fgets($fp))) {
            if ($i++ < $offset) {
                continue;
            }
            break;
        }
        $data = array();
        while (($j++ < $lines) && !feof($fp)) {
            $data[] = fgetcsv($fp);
        }
        fclose($fp);
        return $data;
    }
}
